package cringer::fetchfeed;

# fetchfeed.pm
# updates feeds via the GAJAX Feeds API, just because  we can.

use JSON;

sub said{
 my $self = $_[0];
 my $args = $_[1];
 my $me = $self->{nick};
 
 unless($args->{body} =~ /^(find|lookup|load)feed: ?(.*)$/i){ # if this isn't a search query, we skip it.
  return;
 }

 my $mode = lc($1);
 my $q = $2;
 my @r; # set up the response array
 my $url = qq~http://ajax.googleapis.com/ajax/services/feed/$mode?v=1.0&q=~ . cringer::uriencode($q);
 my $r = $self->{ua}->get($url);
 my $json;
 eval { $json = from_json($r->decoded_content); };
 if(($@ ne '') || defined($json->{responseData}->{error})){
  print qq~\n================\nFeed error:\n~ . $r->decoded_content . qq~\nError: $@\n================\n~;
  return qq~I'm sorry, but I encountered an error processing your query.~;
 }
 
 my $responseData = $json->{responseData};
 if($mode eq 'find'){
  my @results = @{$responseData->{entries}};
  my $numResults = @results;
  push(@r, qq~$numResults found for "$q":~);
  my $num = 1;
  foreach my $result (@results){
   $result->{title} =~ s/\<[^\>]+\>//g;
   push(@r, qq~$num. $result->{title} ( $result->{link} )~);
   $num++;
  }
 } elsif ($mode eq 'lookup') {
  push(@r, cringer::gtg($responseData->{url}) ? qq~Feed for $q: $responseData->{url}~ : qq~No feed found for $q~);
 } else {
  my @results = @{$responseData->{feed}->{entries}};
  my $numResults = @results;
  push(@r, qq~Showing $numResults from $responseData->{feed}->{title}:~);
  my $num = 1;
  foreach my $result (@results){
   push(@r, qq~$num. $result->{title} - $result->{publishedDate} ( $result->{link} )~);
   $num++;
  }
 }
 return @r;
}

sub commandList{ # a simple help routine to return a list of the commands we'll respond to
 return qq~loadfeed: [url] : findfeed: [query] | lookupfeed: [url]~;
}

return 1;
